package com.anolesoft.twelvePlan.listener;


import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.CellExtra;
import com.alibaba.excel.read.listener.ReadListener;
import com.anolesoft.twelvePlan.dto.PlanCheckImport;
import com.anolesoft.twelvePlan.entity.MesPlanXiaDaDO;
import com.anolesoft.twelvePlan.service.PlanCheckService;
import com.anolesoft.yr.util.CommonUtils;
import lombok.extern.slf4j.Slf4j;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author zyq
 * @date 2022/7/29
 */
@Slf4j
public class PlanCheckListener implements ReadListener<PlanCheckImport> {

    private static final int BATCH_COUNT = 1000;

    private List<PlanCheckImport> list = new ArrayList<>();

    private List<MesPlanXiaDaDO> communityList = new ArrayList<>(BATCH_COUNT);

    private PlanCheckService planCheckService;

    public PlanCheckListener(PlanCheckService planCheckService) {
        this.planCheckService = planCheckService;
    }

    @Override
    public void onException(Exception e, AnalysisContext analysisContext) throws Exception {

    }

    @Override
    public void invokeHead(Map<Integer, CellData> map, AnalysisContext analysisContext) {

    }

    @Override
    public void invoke(PlanCheckImport planCheckImport, AnalysisContext analysisContext) {
        log.debug("导入数据：{}",planCheckImport);
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDateTime time;
        String plantimeString = planCheckImport.getPlantime();
        if (!StrUtil.isEmptyOrUndefined(CommonUtils.stringNull(plantimeString))) {
            time = LocalDate.parse(plantimeString, df).atStartOfDay();
        } else {
            time = null;
        }
        //MesPlanXiaDaDO mesPlanXiaDaDO;
        MesPlanXiaDaDO mesPlanXiaDaDO = MesPlanXiaDaDO.builder()
                .objuid(CommonUtils.stringNull(planCheckImport.getObjuid()))
                .plantime(time)
                .waixie(CommonUtils.stringNull(planCheckImport.getWaixie()))
                .build();
        communityList.add(mesPlanXiaDaDO);
        if (communityList.size() >= BATCH_COUNT) {
            batchUpdate();
            communityList.clear();
        }
    }

    @Override
    public void extra(CellExtra cellExtra, AnalysisContext analysisContext) {

    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        batchUpdate();
    }

    @Override
    public boolean hasNext(AnalysisContext analysisContext) {
        return true;
    }

    void batchUpdate() {
        log.debug("数据：{}", communityList);
        planCheckService.uploadCheck(communityList);
    }
}
